package com.byron.pss.template;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.byron.pss.util.JdbcUtils;

/**
 * jdbc操作的模板类
 */
public class JdbcTemplate {

	/**
	 * DML操作模板
	 * @param sql
	 * @param params
	 */
	public static void update(String sql, Object... params) {
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			conn = JdbcUtils.getConnection();
			// 获取语句对象
			ps = conn.prepareStatement(sql);
			// 处理参数
			for (int i = 0; i < params.length; i++) {
				ps.setObject(i + 1, params[i]);
//				System.out.println(params[i]);
			}
//			System.out.println(ps.toString());
			// 执行sql语句
			ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JdbcUtils.close(null, ps, conn);
		}
	}

	public static <T> T query(String sql, IResultHandler<T> handle,
			Object... params) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtils.getConnection();
			ps = conn.prepareStatement(sql);
			// 处理参数
			for (int i = 0; i < params.length; i++) {
				ps.setObject(i + 1, params[i]);
			}
			rs = ps.executeQuery();
			return handle.handle(rs);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JdbcUtils.close(rs, ps, conn);
		}
		return null;
	}
}
